#include "mainwindow.h"
#include "controller.h"

#include <QPainter>
#include <QApplication>

MainWindow::MainWindow(QWidget *parent, Qt::WFlags flags)
: QMainWindow(parent, flags)
, timer ( this )
{
    timer.setSingleShot ( false );
    connect ( & timer, SIGNAL ( timeout()), this, SLOT ( onTimerEvent()));
    timer.start ( 50 );
}

MainWindow::~MainWindow()
{
}

void MainWindow::AddCircle ( int x, int y, int radius, QColor color )
{
    CircleData circleData ( x, y, radius, color );
    circleDataVect.push_back ( circleData );
}

void MainWindow::MoveCircle ( int index, int xTo, int yTo )
{
    ASSERT ( index >= 0 && index < circleDataVect.size());
    circleDataVect[index].x = xTo;
    circleDataVect[index].y = yTo;
}

void MainWindow::SetMassCenter ( const Point2D & massCenter )
{
    this -> massCenter = massCenter;
}

void MainWindow::closeEvent ( QCloseEvent * event )
{
    controller -> Stop();
    controller -> wait();
    qApp -> quit();
}

void MainWindow::SetModel ( Controller * controller )
{
    this -> controller = controller;
}

void MainWindow::paintEvent ( QPaintEvent * e )
{
    QPainter p ( this );
    for ( size_t i = 0; i < circleDataVect.size(); ++i )
    {
        p.setPen ( QPen ( circleDataVect[i].color ));
        p.setBrush ( QBrush ( circleDataVect[i].color ));

        p.drawEllipse ( circleDataVect[i].x - circleDataVect[i].radius, circleDataVect[i].y - circleDataVect[i].radius,
                        circleDataVect[i].radius * 2 - 1, circleDataVect[i].radius * 2 - 1 );
    }
    
    p.setPen ( QPen ( Qt::red ));

    const double cntRadius = 3;
    p.drawEllipse ( massCenter.x - cntRadius, massCenter.y - cntRadius, cntRadius * 2 - 1, cntRadius * 2 - 1 );
}

void MainWindow::onTimerEvent()
{
    repaint();
}
